package ccgl.com.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ccgl.com.model.MUser;
import ccgl.com.server.XtszServer;
import ccgl.com.util.GsonPrint;
import ccgl.com.util.JsonHelper;

public class XtszAction extends BaseServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	HttpServletRequest request = null;
	HttpServletResponse response = null;
	XtszServer server = new XtszServer();

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.request = req;
		this.response = resp;
		req.setCharacterEncoding("UTF-8");
		String control = this.request.getParameter("control");
		if ("changPassword".equals(control)) {
			changPassword();
		} else {
			GsonPrint.printFormatGson("没有请求的control！", this.response);
		}
	}

	private void changPassword() {
		MUser user = (MUser) this.request.getSession().getAttribute("user");
		Password p = null;
		try {
			p = JsonHelper.getObjectByServletRequest(request, Password.class);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		if (user.getPassword().equals(p.getOldPassword())) {
			try {
				if (server.upDatePassword(user.getId(), p.getNewPassword())) {
					GsonPrint.printFormatGson("success", response);
					user.setPassword(p.getNewPassword());
					this.request.getSession().setAttribute("user", user);
				} else {
					GsonPrint.printFormatGson("*error*", response);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			try {
				GsonPrint.printFormatGson("*旧密码不正确*", response);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	private class Password {
		private String oldPassword;
		private String newPassword;

		public String getOldPassword() {
			return oldPassword;
		}

		public void setOldPassword(String oldPassword) {
			this.oldPassword = oldPassword;
		}

		public String getNewPassword() {
			return newPassword;
		}

		public void setNewPassword(String newPassword) {
			this.newPassword = newPassword;
		}

	}
}
